<?php
header('Content-Type: text/html; charset=UTF-8');
require 'crawl.php';
require 'database.php';
$db = new DB();

// Select games ID
$Qry = 'SELECT g_id, crawl_url
		FROM games
		WHERE done = 0
		ORDER BY g_id DESC
		LIMIT 5';
$res = $db->fetchAll($Qry);

foreach ($res as $key=>$value){
	crawl($value['g_id'], $value['crawl_url']);
}
// crawl ( 1, 'http://www.gamepilot.com/game/collecting+platform/super+kaka.htm' );
function crawl($id, $url) {
	global $db;
	$sth = array(
			"'",
			'=',
			'"'
	);

	$status = get_headers($url);
	if ($status[0] == 'HTTP/1.1 404 Not Found'){
		$games = array(
				'done'=>2,
				'active'=>0
		);
		echo $url . ' <font color="red">ERROR 404 - PAGE NOT FOUND</font><br />';
	}else{
		$html = file_get_html($url);

		// summary
		$summary = $html->find("meta[name='description']", 0)->content;
		$summary = trim($summary);

		// Game
		$game_file = preg_replace('/\<!DOCTYPE html\>(.*?)gameSwf/si', '', $html);
		$game_file = preg_replace('/\;(.*?)\<\/html\>/si', '', $game_file);
		$game_file = str_replace($sth, '', $game_file);
		$game_file = strip_tags($game_file);
		$embed = trim($game_file);

		// Width
		$width = preg_replace('/\<!DOCTYPE html\>(.*?)gameWidth/si', '', $html);
		$width = preg_replace('/\;(.*?)\<\/html\>/si', '', $width);
		$width = str_replace($sth, '', $width);
		$width = strip_tags($width);
		$width = (int)$width;

		// Height
		$height = preg_replace('/\<!DOCTYPE html\>(.*?)gameHeight/si', '', $html);
		$height = preg_replace('/\;(.*?)\<\/html\>/si', '', $height);
		$height = str_replace($sth, '', $height);
		$height = strip_tags($height);
		$height = (int)$height;

		// Game info
		$desc = '';
		if ($html->find('div.content > p', 0)){
			$info = $html->find('div.content > p', 0)->innertext;

			$desc = trim($info);
			$desc = str_replace('http://www.gamepilot.com/', '/', $desc);
			$desc = str_replace("'", '&#39;', $desc);
		}

		$query = '';
		$condition = 'g_id = ' . $id;

		if ($embed){
			// echo '<h1>' . $embed . ' ' . $width . 'x' . $height . '</h1>' . $desc;


			$games = array(
					'object'=>$embed,
					'width'=>$width,
					'height'=>$height,
					'summary'=>$summary,
					'description'=>$desc,
					'done'=>1,
					'active'=>1
			);

			echo '<p style="color:green">Game ID ' . $id . ' ==> Okay.</p>';
		}else{
			$games = array(
					'done'=>1,
					'active'=>0
			);

			echo '<p style="color:yellow">Game ID ' . $id . ' ==> can\'t crawl data.</p>';
		}
	}

	$db->update('games', $games, $condition);
}